package io.dbw.modules.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.dbw.modules.business.dao.SysUserTokenDao;
import io.dbw.modules.business.entity.SysUserTokenEntity;
import io.dbw.modules.business.oauth2.TokenGenerator;
import io.dbw.modules.business.service.SysUserTokenService;
import io.dbw.modules.business.vo.LoginUserVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service("sysUserTokenService")
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenDao, SysUserTokenEntity> implements SysUserTokenService {
	/**
	 * 单点登录是否开启,开启true
	 */
	@Value("${common.single.login-switch}")
	private Boolean singleLoginSwitch;
	/**
	 * token有效时间(单位S)
	 */
	@Value("${common.token.expire}")
	private Integer tokenExpire;


	@Override
	public LoginUserVO createToken(long userId ) {
		//生成一个token
		String token = TokenGenerator.generateValue();
		//当前时间
		Date now = new Date();
		LoginUserVO loginUserVO=new LoginUserVO();
		//查询公司信息
		Date expireTime = new Date(now.getTime() + tokenExpire * 1000);
		if (!singleLoginSwitch) {
			SysUserTokenEntity tokenEntity = new SysUserTokenEntity();
			tokenEntity.setUserId(userId);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setToken(token);
			tokenEntity.setExpireTime(expireTime);
			this.save(tokenEntity);
		} else {
			//判断是否生成过token
			SysUserTokenEntity tokenEntity = this.getById(userId);
			if (tokenEntity == null) {
				tokenEntity = new SysUserTokenEntity();
				tokenEntity.setUserId(userId);
				tokenEntity.setToken(token);
				tokenEntity.setUpdateTime(now);
				tokenEntity.setExpireTime(expireTime);
				//保存token
				this.save(tokenEntity);
			} else {
				tokenEntity.setToken(token);
				tokenEntity.setUpdateTime(now);
				tokenEntity.setExpireTime(expireTime);
				//更新token
				this.updateById(tokenEntity);
			}
		}
		loginUserVO.setExpire(tokenExpire);
		loginUserVO.setToken(token);
		return loginUserVO;
	}

	@Override
	public void logout(String token) {
		this.remove(new QueryWrapper<SysUserTokenEntity>().eq("token",token));
	}
}
